<?php 
namespace app\wework\model\user\promotion;
use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;

/**
* 自动推广码
**/
class BuffetPromotionModel {
	/*
	* 列表
	*/
	static public function list($type,$page,$size){
		$wid = Session::get("wid");
		$where["wid"] = $wid;
		$where["type"] = $type;
		$res = Db::table("kt_wework_promotion")
					->where($where);
		$data["count"] = $res->count();
		$data["item"] = $res->page($page,$size)
					->field("staffs,name,status,ctime,id")
					->json(["staffs"])
					->filter(function($data){
						$data["staffs"] = Db::table("kt_wework_staff")->where(['id'=>$data["staffs"]])->column("name");
						$data["browse_count"] = 0;
						$data["add_count"] = 0;
						return $data;
					})
					->select()
					->toArray();
		$data["page"] = $page;
		$data["size"] = $size;

		return $data;
	}

	static public function add($data,$url){
		$wid = Session::get("wid");
		$data["wid"] = $wid;
		if($data["type"] == 1 && !$data["staffs"])return error("请选择成员");
		if($data["type"] == 2 && !$data["group_data"])return error("请上传群信息");
		if(!isset($data["id"])){
			for ($i=0; $i < count($data["group_data"]); $i++) {
				$data["group_data"][$i]["status"] = 2;
			}
			$data["group_data"][0]["status"] = 1;
		}
		$user_list = Db::table("kt_wework_staff")->where(["id"=>$data["staffs"]])->column("userid");
		if(isset($data["id"])){
			$id = $data["id"];
			$info = self::info($id);
			if($data["type"] == 1){
				$params['user'] = $user_list;
				$params['config_id'] = $info["config_id"];
				$upd = QyWechatApi::updateContactWay($params);
				if($upd["errcode"] != 0)return error("修改渠道码错误",$upd["errcode"]);
			}else{
				$upd_welcome = QyWechatApi::editWelcomeTemplate($wid,$info["template_id"],$data["group_welcome"]);
				if($upd_welcome["errcode"] != 0)return error("修改入群欢迎语错误",$upd_welcome["errcode"]);
			}
			Db::table("kt_wework_promotion")->where(["id"=>$id])->json(["staffs","group_data","welcome_list","tags","h5_tow_style"])->save($data);
		}else{
			$data["ctime"] = date("Y-m-d H:i:s");
			$id = Db::table("kt_wework_promotion")->json(["staffs","group_data","welcome_list","tags","h5_tow_style"])->insertGetId($data);
			if($data["type"] == 1){
				$params['type'] = 2;
				$params['scene'] = 2;
				$params['user'] = $user_list;
				$params['state'] = "pro_".$id;
				$params['skip_verify'] = true;
				$add_way = QyWechatApi::addContactWay($params);
				if($add_way["errcode"] != 0){
					Db::table("kt_wework_promotion")->where(["id"=>$id])->delete();
					return error("创建渠道码错误",$add_way["errcode"]);
				}
				$upd["state"] = $params['state'];
				$upd["config_id"] = $add_way['config_id'];
				$upd["qr_code"] = $add_way['qr_code'];
			}else if($data["type"] == 2){
				$add_welcome = QyWechatApi::groupWelcomeTemplate($wid,$data["group_welcome"]);
				if($add_welcome["errcode"] != 0){
					Db::table("kt_wework_promotion")->where(["id"=>$id])->delete();
					return error("创建入群欢迎语错误",$add_welcome["errcode"]);
				}
				$upd["template_id"] = $add_welcome["template_id"];
			}
			Db::table("kt_wework_promotion")->where(["id"=>$id])->save($upd);
		}
		$str = "【任务提醒-自助推广码-推广码：".$data['name']."】您有新的任务哦！";
		$str .= "<br>";
		$str .= "<br>";
		$str .= "任务类型：推广任务";
		$str .= "<br>";
		$str .= "<br>";
		if($data['type'] == 1)$str .= "任务内容：添加企业微信";
		if($data['type'] == 2)$str .= "任务内容：邀请客户入群";
		$str .= "<br>";
		$str .= "<br>";
		$str .= "任务说明： ".$data['task_state'];
		$user_list = implode("|",$user_list);
		$res = QyWechatApi::send_textcard($user_list,$wid,"自助推广码提醒",$str,$url.'/wework/h5.BuffetPromotion/index.html?id='.$id);
		if($data["type"] == 2){
			foreach ($group_data as $group){
				$groups = Db::table("kt_wework_group")->where(["id"=>$group["id"]])->find();
				$content = "管理员提醒您给客户群'{$name}'配置欢迎语，请在客户群联系中，查看配置内容，并选择群'{$name}'进行配置";
				$userid = Db::table("kt_wework_staff")->field("userid")->where(["id"=>$group["staff_id"]])->find()["userid"];
				QyWechatApi::sendText($wid,$userid,$content);
			}
		}

		return success("操作成功",$res);
	}

	static public function info($id){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_promotion")->where(["id"=>$id])->json(["staffs","tags","h5_tow_style","welcome_list"])->find();
		$res["staffs_list"] = Db::table("kt_wework_staff")->where(["id"=>$res["staffs"]])->field('name,avatar')->select()->toArray();
		$res["tag_info"] = Db::table("kt_wework_tag")->where(["tag_id"=>$res["tags"],"wid"=>$wid])->field('tag_name')->select()->toArray();

		return $res;
	}

	static public function infos($id){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_promotion")->where(["id"=>$id])->field("name,staffs,remin_status,ttime,task_state,promotion_welcome,promotion_type,end_time,welcome_text,is_tag,tags,is_bz,bz,is_describe,describe,h5_title,h5_type,h5_one_logo,h5_one_qyname,h5_one_is_introduce,h5_one_introduce,h5_one_guidance,h5_tow_bg,h5_tow_style")->json(["staffs","tags","h5_tow_style"])->find();
		$res["staffs"] = Db::table("kt_wework_staff")->where(["id"=>$res["staffs"]])->field('name,avatar')->select()->toArray();
		$res["tags"] = Db::table("kt_wework_tag")->where(["tag_id"=>$res["tags"],"wid"=>$wid])->field('tag_name')->select()->toArray();


		return $res;
	}

	static public function del($id){
		$wid = Session::get("wid");
		$info = self::info($id);
		if($info["config_id"]){
			$del = QyWechatApi::delContactWay($info["config_id"],$wid);
			if($del["errcode"] != 0)return error("创建入群欢迎语错误",$add_welcome["errcode"]);
		}
		$res = Db::table("kt_wework_promotion")->where(["id"=>$id])->delete();
		
		return success("操作成功",$res);
	}

	static public function promotions($where){
		$res = Db::table("kt_wework_promotion")->where($where)->select()->toArray();

		return $res;
	}

	static public function statistics($id){
		$wid = Session::get("wid");
		$data["browsesize_all"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1])->count();//浏览次数
		$data["addsize_all"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2])->count();//添加次数
		$data["delsize_all"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3])->count();//删除流失次数
		$data["add_all"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0])->count();;//全部净增
		$time = date("Y-m-d");
		$data["browsesize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1])->whereTime("ctime",">=",$time)->count();//今日浏览次数
		$data["addsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2])->whereTime("ctime",">=",$time)->count();//今日添加次数
		$data["delsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3])->whereTime("ctime",">=",$time)->count();//今日删除流失次数
		$data["add"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0])->whereTime("ctime",">=",$time)->count();//今日净增

		return $data;
	}

	static public function one(){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_promotion")->where(["wid"=>$wid])->min("id");

		return $res;
	}

	static public function map($id,$type,$ktime,$dtime){
		$wid = Session::get("wid");
		if($type == 1){
			$time = strtotime($dtime) - strtotime($ktime);
			$time_tow = $ktime;
			for ($i=0;$i<=$time/(3600*24);$i++){
				$time_one = date("Y-m-d",strtotime($time_tow));
				$time_tow = date("Y-m-d",strtotime($time_tow)+3600*24);
				$times[] = $time_one;
				$browsesize[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$addsize[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$delsize[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$add[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
			}
			$res["time"] = $times;
			$res["browsesize"] = $browsesize;
			$res["addsize"] = $addsize;
			$res["delsize"] = $delsize;
			$res["add"] = $add;
		}else{
			$promotion = Db::table("kt_wework_promotion")->where(["id"=>$id])->json(["staffs"])->find();
			$staff = $promotion["staffs"];
			$list = Db::table("kt_wework_promotion_size")->where(["wid"=>$wid,"pid"=>$id])->field("staff_id,count(*) num")->group("staff_id")->order("num desc")->page(1,10)->select()->toArray();
			foreach ($list as $value){
				$num[] = $value["num"];
				$staff =  Db::table("kt_wework_staff")->where(["id"=>$value["staff_id"]])->find();
				$name[] = $staff["name"];
				$addsize[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2,"staff_id"=>$value["staff_id"]])->count();
				$delsize[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3,"staff_id"=>$value["staff_id"]])->count();
				$add[] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0,"staff_id"=>$value["staff_id"]])->count();
			}
			$res["num"] = $num;
			$res["name"] = $name;
			$res["addsize"] = $addsize;
			$res["delsize"] = $delsize;
			$res["add"] = $add;
		}
		
		return $res;
	}

 	static public function table($id,$type,$ktime,$dtime){
 		$wid = Session::get("wid");
		$res = [];
 		if($type == 2){
 			$time = strtotime($dtime) - strtotime($ktime);
			$time_tow = $ktime;
			for ($i=0;$i<=$time/(3600*24);$i++){
				$time_one = date("Y-m-d",strtotime($time_tow));
				$time_tow = date("Y-m-d",strtotime($time_tow)+3600*24);
				$res[$i]["times"] = $time_one;
				$res[$i]["browsesize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$res[$i]["addsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$res[$i]["delsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
				$res[$i]["add"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0])->whereBetweenTime("ctime",$time_one,$time_tow)->count();
			}
 		}else{
 			$list = Db::table("kt_wework_promotion_size")->where(["wid"=>$wid,"pid"=>$id])->field("staff_id,count(*) num")->group("staff_id")-》order("num desc")->select()->toArray();
 			foreach ($list as $key=>$value){
				$res[$key]["ranking"] = $key+1;
				$res[$key]["num"] = $value["num"];
				$staff =  Db::table("kt_wework_staff")->where(["id"=>$value["staff_id"]])->find();
				$res[$key]["name"] = $staff["name"];
				$res[$key]["avatar"] = $staff["avatar"];
				$res[$key]["addsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>2,"staff_id"=>$value["staff_id"]])->count();
				$res[$key]["delsize"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>3,"staff_id"=>$value["staff_id"]])->count();
				$res[$key]["add"] = Db::table("kt_wework_promotion_size")->where(["pid"=>$id,"type"=>1,"is_qun"=>0,"staff_id"=>$value["staff_id"]])->count();
			}
 		}

 		return $res;
 	}
}